//
//  NoticeDetailViewController.m
//  Supervisor
//
//  Created by 小宇 on 2017/5/15.
//  Copyright © 2017年 北京怀教网络科技股份有限公司. All rights reserved.
//

#import "NoticeDetailViewController.h"
#import "UILabel+labelHeight.h"
#import "LZYDownloaderManager.h"
#import "LZYFileTool.h"
#import "DownLoadModel.h"

@interface NoticeDetailViewController ()<UIWebViewDelegate,UIDocumentInteractionControllerDelegate>
@property (nonatomic, assign)float webViewHeight;
@property (nonatomic, assign)NSInteger filecount;
@property (nonatomic, strong)NSDictionary * responseDic;
@property (nonatomic, strong)UIView * titleView;
@property (nonatomic, strong)UIView * downLoadView;
@property (nonatomic, strong)UIWebView * webView;
@property (nonatomic, strong)UIScrollView * scrollView;
@property (nonatomic, strong)NSDictionary * parameterDic;
@property (nonatomic, strong) UIDocumentInteractionController *documentController;
@property (nonatomic, copy)NSString * url;
@end

@implementation NoticeDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (NSString *)setNavTitle{
    return @"公告详情";
}

- (NSDictionary *)sendParameterWithGet{
    LZYWeakSelf(self);
    self.netWorkBlock = ^(id responseDic) {
        weakself.responseDic = responseDic;
        weakself.filecount = [responseDic[@"files"] count];
        [weakself.view addSubview:weakself.scrollView];
        [weakself.scrollView addSubview:[weakself titleViewWithResponseDic:responseDic]];
        [weakself.scrollView addSubview:[weakself webViewWithContent:responseDic[@"notice"][@"content"]]];
    };
    self.parameterDic = @{@"id":@(self.noticeId)};
    self.url = noticeview;
    NSDictionary *dic = @{@"parameterDic":self.parameterDic,@"url":self.url};
    return dic;
}

- (UIScrollView *)scrollView{
    if (!_scrollView) {
        _scrollView = [[UIScrollView alloc] init];
        _scrollView.frame = CGRectMake(0, 0, Main_Screen_Width, Main_View_Height);
        _scrollView.backgroundColor = [UIColor whiteColor];
        _scrollView.contentSize = CGSizeMake(0, 1);
    }
    return _scrollView;
}

- (UIView *)titleViewWithResponseDic:(NSDictionary *)responseDic{
    if (!_titleView) {
        CGFloat labelHeight = [UILabel getSpaceLabelHeight:responseDic[@"notice"][@"title"] withWidh:Main_Screen_Width - 15] > 21 ? [UILabel getSpaceLabelHeight:responseDic[@"notice"][@"title"] withWidh:Main_Screen_Width - 30] : 21;
        _titleView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 50 + labelHeight)];
        UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, Main_Screen_Width, 5)];
        lineView.backgroundColor = BackgroundColor;
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, 15, Main_Screen_Width - 30, labelHeight) Text:responseDic[@"notice"][@"title"] TextColor:GeneralFontColor TextAlignment:NSTextAlignmentLeft Font:[UIFont systemFontOfSize:15] Target:nil Action:nil];
        titleLabel.numberOfLines = 0;
        [_titleView addSubview:titleLabel];
        UILabel *nameAndTimeLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, labelHeight + 22, Main_Screen_Width - 15, 16.5) Text:[NSString stringWithFormat:@"%@ %@",responseDic[@"notice"][@"sendername"],[responseDic[@"notice"][@"createTime"] substringToIndex:16]] TextColor:WeekFontColor TextAlignment:NSTextAlignmentLeft Font:AdaptedFontSize(12) Target:nil Action:nil];
        [_titleView addSubview:lineView];
        [_titleView addSubview:titleLabel];
        [_titleView addSubview:nameAndTimeLabel];
        _titleView.backgroundColor = [UIColor whiteColor];
        self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.titleView.frame));
    }
    return _titleView;
}

- (UIWebView *)webViewWithContent:(NSString *)content{
    if(!_webView){
        _webView = [[UIWebView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(self.titleView.frame), Main_Screen_Width - 30, 1)];
        _webView.scrollView.bounces = NO;
        _webView.scrollView.scrollEnabled = NO;
        _webView.delegate = self;
        [_webView.scrollView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew context:nil];
        _webView.layer.cornerRadius = 4;
        _webView.layer.masksToBounds = YES;
        _webView.layer.borderColor = LineColor.CGColor;
        _webView.layer.borderWidth = 1;
        [_webView loadHTMLString:content baseURL:nil];
    }
    return _webView;
}

- (UIView *)downLoadViewWithFileList:(NSArray *)fileList{
    if (!_downLoadView) {
        _downLoadView = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.webView.frame) + 14.5, Main_Screen_Width, 44 + fileList.count * 55)];
        _downLoadView.backgroundColor = [UIColor whiteColor];
        UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 14, 35, 21) Text:@"附件" TextColor:GeneralFontColor TextAlignment:NSTextAlignmentCenter Font:AdaptedFontSize(15) Target:nil Action:nil];
        
        for (int i = 0; i < fileList.count; i ++) {
            UIView *fileView = [[UIView alloc]initWithFrame:CGRectMake(15, 44 + (i * 55), Main_Screen_Width - 30, 40)];
            fileView.tag = 1000 + i;
            fileView.userInteractionEnabled = YES;
            UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(downLoadFile:)];
            fileView.backgroundColor = [UIColor colorWithHexString:@"#EEF8FF"];
            [fileView addGestureRecognizer:tap];
            
            UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 11.5, 14, 15)];
            imgView.image = GetImage(@"file");
            UILabel *fileName = [[UILabel alloc]initWithFrame:CGRectMake(30, 12, Main_Screen_Width - 125, 16.5) Text:fileList[i][@"filename"] TextColor:GeneralFontColor TextAlignment:NSTextAlignmentLeft Font:AdaptedFontSize(12) Target:nil Action:nil];
            UILabel *filesize = [[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(fileName.frame) + 11, 12, 50, 16.5) Text:[NSString stringWithFormat:@"%@",[fileList[i][@"filesize"] integerValue] < 1024 ? [NSString stringWithFormat:@"%@KB",fileList[i][@"filesize"]] : [NSString stringWithFormat:@"%.0ldM",[fileList[i][@"filesize"]integerValue]/1024]] TextColor:GeneralFontColor TextAlignment:NSTextAlignmentLeft Font:AdaptedFontSize(12) Target:nil Action:nil];
            
            [fileView addSubview:imgView];
            [fileView addSubview:fileName];
            [fileView addSubview:filesize];
            [_downLoadView addSubview:fileView];
        }
        [_downLoadView addSubview:label];
        [_downLoadView setAllCornerWithCornerRadius:4];
        _downLoadView.layer.borderColor = LineColor.CGColor;
        _downLoadView.layer.borderWidth = 0.5;
    }
    return _downLoadView;
}

//检测webview展示高度
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context

{
    if ([keyPath isEqualToString:@"contentSize"]) {
        self.webViewHeight = [[self.webView stringByEvaluatingJavaScriptFromString:@"document.body.scrollHeight"] floatValue];
        self.webView.frame = CGRectMake(15, CGRectGetMaxY(self.titleView.frame), Main_Screen_Width - 30, self.webViewHeight > 100 ? self.webViewHeight : 100);
        self.scrollView.contentSize = CGSizeMake(0, CGRectGetMaxY(self.titleView.frame) +  self.webViewHeight + (self.filecount > 0 ? 55 + self.filecount * 55 : 0));
        if (self.filecount > 0) {
            [self.scrollView addSubview:[self downLoadViewWithFileList:self.responseDic[@"files"]]];
        }
    }
}

- (void)downLoadFile:(UITapGestureRecognizer *)tap{
    NSURL *fileUrl = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",DigitalCampus_FileUrl,self.responseDic[@"files"][tap.view.tag - 1000][@"filepath"]]];
    
    if ([LZYDownLoader cachePathWithURL:fileUrl]) {
        NSURL *cachePath = [NSURL URLWithString:[NSString stringWithFormat:@"file://%@",[kPathCache stringByAppendingPathComponent:fileUrl.lastPathComponent]]];
        self.documentController =[UIDocumentInteractionController interactionControllerWithURL:cachePath];
        self.documentController.delegate = self;
        [self.documentController presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
    }else{
        LZYWeakSelf(self)
        [[LZYDownloaderManager shareInstance]downLoadWithURL:fileUrl fileInfo:^(long long totalFileSize) {
            
        } success:^(NSString *cachePath, long long totalFileSize) {
            [SVProgressHUD dismiss];
            [LZYShowMsg showText:@"下载完成"];
            DownLoadModel *downLoadModel = [[DownLoadModel alloc]init];
            downLoadModel.cachePath = [kPathCache stringByAppendingPathComponent:cachePath.lastPathComponent];
            downLoadModel.titleName = weakself.responseDic[@"files"][tap.view.tag - 1000][@"filename"];
            downLoadModel.byName = weakself.responseDic[@"notice"][@"sendername"];
            downLoadModel.upLoadTime = [weakself.responseDic[@"notice"][@"createTime"] substringToIndex:16];
            downLoadModel.downloadId = [NSString stringWithFormat:@"%@",weakself.responseDic[@"files"][tap.view.tag - 1000][@"id"]];
            [LZYModelOperationTool saveModel:downLoadModel withUserID:[[User shareInstance] getUserId]];
            self.documentController =[UIDocumentInteractionController interactionControllerWithURL:[NSURL fileURLWithPath:downLoadModel.cachePath]];
            self.documentController.delegate = self;
            [self.documentController presentOptionsMenuFromRect:self.view.bounds inView:self.view animated:YES];
        } fail:^(NSString *errorMsg) {
            [LZYShowMsg showText:@"下载失败"];
        } progress:^(float progress) {
            [SVProgressHUD showProgress:progress status:@"下载中，请等待..."];
        } state:^(LZYDownLoaderState state) {
            
        }];
    }

}

- (UIViewController *)documentInteractionControllerViewControllerForPreview:(UIDocumentInteractionController *)controller
{
    return self;
}

- (UIView *)documentInteractionControllerViewForPreview:(UIDocumentInteractionController *)controller
{
    return self.view;
}

- (CGRect)documentInteractionControllerRectForPreview:(UIDocumentInteractionController *)controller
{
    return  self.view.frame;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)dealloc{
        [self.webView.scrollView removeObserver:self forKeyPath:@"contentSize" context:nil];
}

@end
